package com.xuelang.pipeline.domain.resource.service.impl;

import com.xuelang.pipeline.client.common.exception.BizException;
import com.xuelang.pipeline.client.common.result.PageRecord;
import com.xuelang.pipeline.client.resource.dto.CloudEnvironmentQuery;
import com.xuelang.pipeline.domain.resource.CloudEnvironment;
import com.xuelang.pipeline.domain.resource.repository.CloudEnvironmentRepository;
import com.xuelang.pipeline.domain.resource.service.CloudEnvironmentDomainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 多云环境领域服务实现类
 *
 * @author xiwen.zxg
 * @since 2024/5/15
 */
@Service
public class CloudEnvironmentDomainServiceImpl implements CloudEnvironmentDomainService {

    @Autowired
    private CloudEnvironmentRepository cloudEnvironmentRepository;

    @Override
    public PageRecord<CloudEnvironment> pageList(long currentPage, long pageSize, CloudEnvironmentQuery cloudEnvironmentQuery) {
        return cloudEnvironmentRepository.pageList(currentPage, pageSize, cloudEnvironmentQuery);
    }

    @Override
    public List<CloudEnvironment> list(CloudEnvironmentQuery cloudEnvironmentQuery) {
        return cloudEnvironmentRepository.list(cloudEnvironmentQuery);
    }

    @Override
    public Boolean save(CloudEnvironment cloudEnvironment) {
        if(existsName(cloudEnvironment.getId(), cloudEnvironment.getName())) {
            throw new BizException("name已经存在");
        }
        if(existsName(cloudEnvironment.getId(), cloudEnvironment.getAlias())) {
            throw new BizException("alias已经存在");
        }
        return cloudEnvironmentRepository.save(cloudEnvironment);
    }

    @Override
    public Boolean update(CloudEnvironment cloudEnvironment) {
        // 更新时，名称不能重复，摒弃多云环境的名称。
        if(existsName(cloudEnvironment.getId(), cloudEnvironment.getName())) {
            throw new BizException("name已经存在");
        }
        // 更新时，别名不能重复，摒弃多云环境的别名。
        if(existsAlias(cloudEnvironment.getId(), cloudEnvironment.getAlias())) {
            throw new BizException("alias已经存在");
        }
        return cloudEnvironmentRepository.update(cloudEnvironment);
    }

    @Override
    public Boolean delete(Long id) {
        return cloudEnvironmentRepository.delete(id);
    }

    @Override
    public CloudEnvironment query(Long id) {
        return cloudEnvironmentRepository.query(id);
    }

    @Override
    public Boolean existsName(Long id, String name) {
        return cloudEnvironmentRepository.existsName(id, name);
    }

    @Override
    public Boolean existsAlias(Long id, String alias) {
        return cloudEnvironmentRepository.existsAlias(id, alias);
    }

}
